<?php

namespace App\Http\Controllers;

use App\Models\Member;
use Artisan;
use EasyWeChat\OfficialAccount\Application;
use Log;

class WeChatController extends Controller
{

    /**
     * 处理微信的请求消息
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \ReflectionException
     */
    public function serve()
    {
        Log::info('request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志

        /** @var Application $app */
        $app = app('wechat.official_account');
        $app->server->push(function ($message) {
            $openid = $message['FromUserName'];
            $member = Member::whereOpenid($openid)->first();
            if (!$member instanceof Member) {
                $member         = new Member();
                $member->openid = $openid;
                $member->save();
            }
            switch ($message['MsgType']) {
                case 'event':
                    return '收到事件消息';
                    break;
                case 'text':
                    if ($message['Content'] == '更新') {
                        Artisan::call('discover');
                        return '更新中';
                    }
                    if ($message['Content'] == '招聘') {
                        return '<a href="http://feier.bicobrand.com">肥二揾工</a>';
                    }
                    return '收到文字消息';
                    break;
                case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                case 'file':
                    return '收到文件消息';
                // ... 其它消息
                default:
                    return '收到其它消息';
                    break;
            }
        });

        return $app->server->serve();
    }
}